package cn.jiawei.jsql.net;

import cn.jiawei.jsql.net.protocol.handler.JsqlChildHandler;
import cn.jiawei.jsql.config.ServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : willian fu
 * @version : 1.0
 * @date : 2020/12/18 0018 14:29
 * 网络服务启动器
 */
//@Log4j
public class JsqlServer {


    public static void run(){
        run(ServerConfig.PORT);
    }

    public static void run(int port){
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new JsqlChildHandler())
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, ServerConfig.HEARTBEAT)
                    .option(ChannelOption.SO_TIMEOUT, ServerConfig.RESPONSE_TIMEOUT);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {

        }
    }
}
